/*
 * @Description: 
 * @Author: paddies
 * @Date: 2024-06-01 13:20:14
 * @LastEditors: paddies
 * @LastEditTime: 2024-08-27 13:06:31
 * @FilePath: /shared_components/lib/luntai-components/login-panel/controller.dart
 */
import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:shared_components/build-common/buildCommon.dart';
import 'package:shared_components/luntai-components/login-panel/state.dart';

class LoginPanelPageController extends GetxController {
  final LoginPanelPageState state = LoginPanelPageState();
  final TextEditingController loginPhoneInputController =
      TextEditingController();

  //统一信用代码输入控制器
  final TextEditingController registerCertificateCodeInputController =
      TextEditingController();
  //公司名称输入控制器
  final TextEditingController registerStoreNameInputController =
      TextEditingController();

  //公司地址输入控制器
  final TextEditingController registerAddressInputController =
      TextEditingController();

  //身份证输入控制器
  final TextEditingController registerIdNumberInputController =
      TextEditingController();

  //身份证输入控制器
  final TextEditingController registerUserNameInputController =
      TextEditingController();
//车牌输入控制器
  final TextEditingController registerCarNumberInputController =
      TextEditingController();

  final TextEditingController registerDriverNameInputController =
      TextEditingController();

  //切换 tab
  void changeTab(int index) {
    state.activeTab.value = index;
    if (index == 0) {
      state.registerPhone.value = "";
      state.registerCode.value = "";
      state.registerPassword.value = "";
      state.registerInviteCode.value = "";
      state.registerAgainPassword.value = "";
    }
    if (index == 2) {
      state.findPhone.value = "";
      state.findCode.value = "";
      state.findNewPassword.value = "";
      state.findAgainNewPassword.value = "";
    }
  }

  String getTabName(int index) {
    return showText(state.tabList.value[index]["label"]);
  }

  //处理密码登录逻辑
  void handleLogin(
      {required Function loginSuccess,
      required Function({String userAccount, String password})
          loginAPI}) async {
    var userAccount = state.loginPhone.value;
    var password = state.loginPassword.value;

    if (userAccount.isEmpty) {
      EasyLoading.showToast("请输入手机号");
      return;
    }

    if (password.isEmpty) {
      EasyLoading.showToast("请输入密码");
      return;
    }

    //检查同意按钮
    var isRead = state.isRead.value;
    if (!isRead) {
      EasyLoading.showToast("请勾选同意按钮");
      return;
    }

    var data = await loginAPI(userAccount: userAccount, password: password);
    // var data = await doLogin(userAccount: userAccount, password: password);
    resetLoginInfo();
    //抛出给使用者处理逻辑
    loginSuccess(data);
    // GlobalPrefs.saveToken(data["access_token"]);
    // Get.offUntil(MaterialPageRoute(builder: (context) {
    //   return LayoutPage();
    // }), (route) => false);
  }

  //重置登录信息
  void resetLoginInfo() {
    state.loginPhone.value = "";
    state.loginPassword.value = "";
    state.isRead.value = false;
    loginPhoneInputController.text = "";
  }

  // 切换勾选已读
  void changeRead() {
    state.isRead.value = !state.isRead.value;
  }

  //处理注册逻辑
  void handleRegister(
      {required String appType,
      required Function registerAPI,
      required Function loginSuccess,
      required Function({String userAccount, String password})
          loginAPI}) async {
    if (appType == 'user') {
      var userAccount = state.registerPhone.value;
      var password = state.registerPassword.value;
      var code = state.registerCode.value;
      var againPassword = state.registerAgainPassword.value;
      var inviteCode = state.registerInviteCode.value;
      if (userAccount.isEmpty) {
        EasyLoading.showToast("请输入手机号");
        return;
      }
      if (code.isEmpty) {
        EasyLoading.showToast("请输入验证码");
        return;
      }
      if (password.isEmpty) {
        EasyLoading.showToast("请输入密码");
        return;
      }
      if (password != againPassword) {
        EasyLoading.showToast("两次密码输入不一致");
        return;
      }

      var res = await registerAPI(
          code: code,
          userAccount: userAccount,
          password: password,
          inviteCode: inviteCode);

      if (res) {
        EasyLoading.showSuccess("注册成功");
        //切换登录面板
        state.activeTab.value = 1;
        //输入登录手机号
        state.loginPhone.value = userAccount;
        loginPhoneInputController.text = userAccount;
        // 延时1s执行返回
        Future.delayed(const Duration(seconds: 2), () {
          handleLogin(loginSuccess: loginSuccess, loginAPI: loginAPI);
        });
      }
    }

    if (appType == 'business') {
      var userAccount = state.registerPhone.value;
      var password = state.registerPassword.value;
      var code = state.registerCode.value;
      var againPassword = state.registerAgainPassword.value;
      var inviteCode = state.registerInviteCode.value;
      var idNumber = state.registerIdNumber.value;
      var idNumberImages = state.registerIdNumberImages.value;
      var storeImageUrl = state.registerStoreImageUrl.value;
      var userName = state.registerUserName.value;
      var address = state.registerAddress.value;
      var storeName = state.registerStoreName.value;

      var businessImages = state.registerBusinessImages.value;

      // var businessCertificateFrontUrl =
      //     state.registerBusinessCertificateFrontUrl.value;
      // var businessCertificateReverseUrl =
      //     state.registerBusinessCertificateReverseUrl.value;
      var certificateCode = state.registerCertificateCode.value;
      if (businessImages.isEmpty) {
        EasyLoading.showToast("请上传营业执照/开户许可证/一般纳税人");
        return;
      }
      if (certificateCode.isEmpty) {
        EasyLoading.showToast("请输入统一社会信用代码");
        return;
      }
      if (storeName.isEmpty) {
        EasyLoading.showToast("请输入公司/店面名称");
        return;
      }
      if (address.isEmpty) {
        EasyLoading.showToast("请输入公司/店面地址");
        return;
      }

      if (idNumber.isEmpty) {
        EasyLoading.showToast("请输入身份证");
        return;
      }
      if (idNumberImages.isEmpty) {
        EasyLoading.showToast("请上传身份证照片");
        return;
      }
      if (userName.isEmpty) {
        EasyLoading.showToast("请输入法人名称");
        return;
      }

      if (storeImageUrl.isEmpty) {
        EasyLoading.showToast("请上传公司/店铺图片");
        return;
      }

      if (userAccount.isEmpty) {
        EasyLoading.showToast("请输入手机号");
        return;
      }

      if (code.isEmpty) {
        EasyLoading.showToast("请输入验证码");
        return;
      }
      if (password.isEmpty) {
        EasyLoading.showToast("请输入密码");
        return;
      }
      if (password != againPassword) {
        EasyLoading.showToast("两次密码输入不一致");
        return;
      }

      var res = await registerAPI(
          code: code,
          userAccount: userAccount,
          password: password,
          businessImages: businessImages.join(","),
          // businessCertificateFrontUrl: businessCertificateFrontUrl.join(","),
          // businessCertificateReverseUrl:
          //     businessCertificateReverseUrl.join(","),
          certificateCode: certificateCode,
          idNumber: idNumber,
          idNumberImages: idNumberImages.join(","),
          userName: userName,
          address: address,
          storeName: storeName,
          storeImageUrl: storeImageUrl.join(","),
          inviteCode: inviteCode);

      if (res) {
        EasyLoading.showSuccess("注册成功");
        //切换登录面板
        state.activeTab.value = 1;
        //输入登录手机号
        state.loginPhone.value = userAccount;
        loginPhoneInputController.text = userAccount;
        // 延时1s执行返回
        Future.delayed(const Duration(seconds: 2), () {
          handleLogin(loginSuccess: loginSuccess, loginAPI: loginAPI);
        });
      }
    }

    if (appType == 'worker') {
      var idNumber = state.registerIdNumber.value;
      var idNumberImages = state.registerIdNumberImages.value;
      var userName = state.registerUserName.value;
      var driveImages = state.registerDriveImages.value;
      var carNumber = state.registerCarNumber.value;
      var driverName = state.registerDriverName.value;
      var userAccount = state.registerPhone.value;
      var password = state.registerPassword.value;
      var code = state.registerCode.value;
      var againPassword = state.registerAgainPassword.value;
      var inviteCode = state.registerInviteCode.value;

      var carCertImages = state.registerCarCertImages.value;

      if (idNumberImages.isEmpty) {
        EasyLoading.showToast("请上传身份改正反面");
        return;
      }
      if (userName.isEmpty) {
        EasyLoading.showToast("请输入身份证姓名");
        return;
      }
      if (idNumber.isEmpty) {
        EasyLoading.showToast("请输入身份证号码");
        return;
      }

      if (carCertImages.isEmpty) {
        EasyLoading.showToast("请上传驾驶证");
        return;
      }

      if (driverName.isEmpty) {
        EasyLoading.showToast("请输入驾驶证姓名");
        return;
      }

      if (driveImages.isEmpty) {
        EasyLoading.showToast("请上传行驶证/流动服务车照片");
        return;
      }

      if (carNumber.isEmpty) {
        EasyLoading.showToast("请输入服务车车牌");
        return;
      }

      if (userAccount.isEmpty) {
        EasyLoading.showToast("请输入手机号");
        return;
      }
      if (code.isEmpty) {
        EasyLoading.showToast("请输入验证码");
        return;
      }
      if (password.isEmpty) {
        EasyLoading.showToast("请输入密码");
        return;
      }
      if (password != againPassword) {
        EasyLoading.showToast("两次密码输入不一致");
        return;
      }

      var res = await registerAPI(
          code: code,
          idNumberImages: idNumberImages.join(","),
          userName: userName,
          idNumber: idNumber,
          driveImages: driveImages.join(","),
          carNumber: carNumber,
          driverName: driverName,
          userAccount: userAccount,
          password: password,
          carCertImages: carCertImages.join(","),
          inviteCode: inviteCode);

      if (res) {
        EasyLoading.showSuccess("注册成功");
        //切换登录面板
        state.activeTab.value = 1;
        //输入登录手机号
        state.loginPhone.value = userAccount;
        loginPhoneInputController.text = userAccount;
        // 延时1s执行返回
        Future.delayed(const Duration(seconds: 2), () {
          handleLogin(loginSuccess: loginSuccess, loginAPI: loginAPI);
        });
      }
    }

    if (appType == 'supplier') {
      var userAccount = state.registerPhone.value;
      var password = state.registerPassword.value;
      var code = state.registerCode.value;
      var againPassword = state.registerAgainPassword.value;
      var inviteCode = state.registerInviteCode.value;
      var idNumber = state.registerIdNumber.value;
      var idNumberImages = state.registerIdNumberImages.value;
      // var storeImageUrl = state.registerStoreImageUrl.value;
      var userName = state.registerUserName.value;
      var address = state.registerAddress.value;
      // var storeName = state.registerStoreName.value;
      var supplierName = state.registerSupplierName.value;

      var businessImages = state.registerBusinessImages.value;
      var certImages = state.registerCertImages.value;

      // var businessCertificateFrontUrl =
      //     state.registerBusinessCertificateFrontUrl.value;
      // var businessCertificateReverseUrl =
      //     state.registerBusinessCertificateReverseUrl.value;
      var certificateCode = state.registerCertificateCode.value;
      if (businessImages.isEmpty) {
        EasyLoading.showToast("请上传营业执照/开户许可证/一般纳税人");
        return;
      }

      if (idNumber.isEmpty) {
        EasyLoading.showToast("请输入身份证");
        return;
      }

      if (address.isEmpty) {
        EasyLoading.showToast("请输入公司/店面地址");
        return;
      }
      if (certImages.isEmpty) {
        EasyLoading.showToast("请上传品牌证书/代理证明");
        return;
      }
      if (idNumberImages.isEmpty) {
        EasyLoading.showToast("请上传身份证照片");
        return;
      }
      if (userName.isEmpty) {
        EasyLoading.showToast("请输入法人名称");
        return;
      }
      if (supplierName.isEmpty) {
        EasyLoading.showToast("请输入供应商名称");
        return;
      }
      if (userAccount.isEmpty) {
        EasyLoading.showToast("请输入手机号");
        return;
      }
      // if (storeName.isEmpty) {
      //   EasyLoading.showToast("请输入店铺名称");
      //   return;
      // }
      // if (storeImageUrl.isEmpty) {
      //   EasyLoading.showToast("请上传店铺图片");
      //   return;
      // }

      if (code.isEmpty) {
        EasyLoading.showToast("请输入验证码");
        return;
      }
      if (password.isEmpty) {
        EasyLoading.showToast("请输入密码");
        return;
      }
      if (password != againPassword) {
        EasyLoading.showToast("两次密码输入不一致");
        return;
      }

      var res = await registerAPI(
          code: code,
          userAccount: userAccount,
          password: password,
          businessImages: businessImages.join(","),
          // businessCertificateFrontUrl: businessCertificateFrontUrl.join(","),
          // businessCertificateReverseUrl:
          //     businessCertificateReverseUrl.join(","),
          certificateCode: certificateCode,
          idNumber: idNumber,
          idNumberImages: idNumberImages.join(","),
          userName: userName,
          address: address,
          supplierName: supplierName,
          certImages: certImages.join(","),
          // storeName: storeName,
          // storeImageUrl: storeImageUrl.join(","),
          inviteCode: inviteCode);

      if (res) {
        EasyLoading.showSuccess("注册成功");
        //切换登录面板
        state.activeTab.value = 1;
        //输入登录手机号
        state.loginPhone.value = userAccount;
        state.registerBusinessCertificateFrontUrl.value = [];
        state.registerBusinessCertificateReverseUrl.value = [];
        state.registerStoreImageUrl.value = [];
        state.registerIdCardImage.value = [];
        loginPhoneInputController.text = userAccount;
        // 延时1s执行返回
        Future.delayed(const Duration(seconds: 2), () {
          handleLogin(loginSuccess: loginSuccess, loginAPI: loginAPI);
        });
      }
    }

    // var res = await doRegister(
    //     code: code,
    //     userAccount: userAccount,
    //     password: password,
    //     inviteCode: inviteCode);

    // if (res) {
    //   EasyLoading.showSuccess("注册成功");
    //   //切换登录面板
    //   state.activeTab.value = 1;
    //   //输入登录手机号
    //   state.loginPhone.value = userAccount;
    //   loginPhoneInputController.text = userAccount;
    //   // 延时1s执行返回
    //   Future.delayed(const Duration(seconds: 2), () {
    //     handleLogin();
    //   });
    // }
  }

  //处理找回密码逻辑
  void handleFindPassword(
      {required Function({String code, String password, String userAccount})
          findPasswordAPI,
      Function? findPasswordSuccess,
      required Function loginSuccess,
      required Function({String userAccount, String password})
          loginAPI}) async {
    var userAccount = state.findPhone.value;
    var password = state.findNewPassword.value;
    var againPassword = state.findAgainNewPassword.value;
    var code = state.findCode.value;

    if (userAccount.isEmpty) {
      EasyLoading.showToast("请输入手机号");
      return;
    }
    if (password.isEmpty) {
      EasyLoading.showToast("请输入新密码");
      return;
    }
    if (code.isEmpty) {
      EasyLoading.showToast("请输入验证码");
      return;
    }
    if (password != againPassword) {
      EasyLoading.showToast("两次输入的密码不一致");
      return;
    }
    var data = await findPasswordAPI(
        code: code, password: password, userAccount: userAccount);
    // //直接去登录
    state.loginPhone.value = userAccount;
    state.loginPassword.value = password;
    state.isRead.value = true;
    //进行登录操作逻辑
    handleLogin(loginSuccess: loginSuccess, loginAPI: loginAPI);
    // findPasswordSuccess();
    // var res = await loginAPI(userAccount: userAccount, password: password);
    // handleLogin();
  }

  //发送找回密码验证码
  void getFindCode({required Function({String mobile}) sendFindCodeAPI}) async {
    if (state.findWaiting.value) {
      return;
    }
    if (state.findPhone.value == "") {
      EasyLoading.showError('请输入手机号！');
      return;
    }

    var data = await sendFindCodeAPI(mobile: state.findPhone.value);
    EasyLoading.showToast("发送成功");
    //进入等待
    findLoopTimer();
  }

  //找回密码验证码等待
  void findLoopTimer() {
    int count = 60;
    const period = Duration(seconds: 1);
    state.findLoop = Timer.periodic(period, (timer) {
      state.findWaiting.value = true;
      count--;
      if (count < 0) {
        //取消定时器，避免无限回调
        timer.cancel();
        state.findWaiting.value = false;
        state.findWaitTitle.value = "重新获取";
        return;
      }
      state.findWaitTitle.value = "重新获取(${count.toString()}s)";
    });
  }

  //发送注册验证码
  void getRegisterCode(
      {required Function({String mobile}) sendRegisterCodeAPI}) async {
    if (state.registerWaiting.value) {
      return;
    }
    if (state.registerPhone.value == "") {
      EasyLoading.showError('请输入手机号！');
      return;
    }

    var data = await sendRegisterCodeAPI(mobile: state.registerPhone.value);
    EasyLoading.showToast("发送成功");
    //进入等待
    registerLoopTimer();
  }

  //注册验证码等待
  void registerLoopTimer() {
    int count = 60;
    const period = Duration(seconds: 1);
    state.registerLoop = Timer.periodic(period, (timer) {
      state.registerWaiting.value = true;
      count--;
      if (count < 0) {
        //取消定时器，避免无限回调
        timer.cancel();
        state.registerWaiting.value = false;
        state.registerWaitTitle.value = "重新获取";
        return;
      }
      state.registerWaitTitle.value = "重新获取(${count.toString()}s)";
    });
  }

  handleOrcData({String imageType = '', dynamic orcData}) {
    if (orcData == null) {
      return;
    }
    if (imageType == "BusinessLicense") {
      var creditCode = showText(orcData["creditCode"]);
      var businessAddress = showText(orcData["businessAddress"]);

      var companyName = showText(orcData["companyName"]);

      var legalPerson = showText(orcData["legalPerson"]);

      if (creditCode.isNotEmpty) {
        registerCertificateCodeInputController.text = creditCode;
        state.registerCertificateCode.value = creditCode;
      }

      if (companyName.isNotEmpty) {
        registerStoreNameInputController.text = companyName;
        state.registerStoreName.value = companyName;
        state.registerSupplierName.value = companyName;
      }

      if (businessAddress.isNotEmpty) {
        registerAddressInputController.text = businessAddress;

        state.registerAddress.value = businessAddress;
      }

      if (legalPerson.isNotEmpty) {
        registerUserNameInputController.text = legalPerson;
        state.registerUserName.value = legalPerson;
      }
    }
    if (imageType == "VehicleLicense") {
      var licensePlateNumber = showText(orcData["licensePlateNumber"]);
      if (licensePlateNumber.isNotEmpty) {
        registerCarNumberInputController.text = licensePlateNumber;
        state.registerCarNumber.value = licensePlateNumber;
      }
    }
    if (imageType == "DrivingLicense") {
      var name = showText(orcData["name"]);

      if (name.isNotEmpty) {
        registerDriverNameInputController.text = name;

        state.registerDriverName.value = name;
      }
    }
    if (imageType == "IdCard") {
      var name = showText(orcData["name"]);
      var idNumber = showText(orcData["idNumber"]);

      if (idNumber.isNotEmpty) {
        registerIdNumberInputController.text = idNumber;

        state.registerIdNumber.value = idNumber;
      }

      if (name.isNotEmpty) {
        registerUserNameInputController.text = name;

        state.registerUserName.value = name;
      }
    }
  }

  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();
  }
}
